#ifndef __M_DB_H__
#define __M_DB_H__
#include <mutex>
#include <cassert>
#include "util.hpp"

class user_table
{
public:
    user_table(const std::string& host,
        const std::string& username,
        const std::string& password,
        const std::string& dbname,
        uint16_t port = 3306)
    {
        _mysql = mysql_util::mysql_create(host, username, password, dbname, port);
        assert(_mysql != nullptr);
    }
    bool insert(Json::Value& user)
    {
#define INSERT_USER "insert user values(null, '%s', sha2('%s', 256), 1000, 0, 0);"
        // 不能缺少用户名或者密码
        if (user["password"].isNull() || user["username"].isNull())
        {
            DLOG("please input password or username");
            return false;
        }

        char sql[4096] = {0};
        sprintf(sql, INSERT_USER, user["username"].asCString(), user["password"].asCString());
        bool ret = mysql_util::mysql_exec(_mysql, sql);
        if (ret == false)
        {
            DLOG("insert user info failed!");
            return false;
        }
        return true;
    }
    bool login(Json::Value& user) // 登录验证，返回详细用户信息
    {
#define LOGIN_USER "select id, score, total_count, win_count from user where username = '%s' and password=sha2('%s', 256);"
        char sql[4096] = {0};
        sprintf(sql, LOGIN_USER, user["username"].asCString(), user["password"].asCString());
        MYSQL_RES* res = nullptr;

        {
            std::unique_lock<std::mutex> lock(_mutex);
            bool ret = mysql_util::mysql_exec(_mysql, sql);
            if (ret == false)
            {
                DLOG("user login failed!");
                return false;
            }
            res = mysql_store_result(_mysql);
            if (res == nullptr)
            {
                DLOG("have no login user info!");
                return false;
            }
        }

        int row_num = mysql_num_rows(res);
        if (row_num != 1) // 确保数据唯一
        {
            DLOG("the user information queried is not unique!");
            return false;
        }
        MYSQL_ROW row = mysql_fetch_row(res);
        user["id"] = std::stol(row[0]);
        user["score"] = std::stol(row[1]);
        user["total_count"] = std::stoi(row[2]);
        user["win_count"] = std::stoi(row[3]);
        mysql_free_result(res);
        return true;
    }
    bool select_by_name(const std::string& name, Json::Value& user)
    {
#define USER_BY_NAME "select id, score, total_count, win_count from user where username='%s';"
        char sql[4096] = {0};
        sprintf(sql, USER_BY_NAME, name.c_str());
        MYSQL_RES* res = nullptr;

        // mysql_exec和mysql_store_result合在一起就不是线程安全的
        {
            std::unique_lock<std::mutex> lock(_mutex);
            bool ret = mysql_util::mysql_exec(_mysql, sql);
            if (ret == false)
            {
                DLOG("get user by name failed!");
                return false;
            }
            res = mysql_store_result(_mysql);
            if (res == nullptr)
            {
                DLOG("have no user info!");
                return false;
            }
        }

        int row_num = mysql_num_rows(res);
        if (row_num != 1)
        {
            DLOG("the user information queried is not unique!");
            return false;
        }
        MYSQL_ROW row = mysql_fetch_row(res);
        user["id"] = std::stol(row[0]);
        user["username"] = name;
        user["score"] = std::stol(row[1]);
        user["total_count"] = std::stoi(row[2]);
        user["win_count"] = std::stoi(row[3]);
        mysql_free_result(res);
        return true;
    }
    bool select_by_id(uint16_t id, Json::Value& user)
    {
#define USER_BY_ID "select username, score, total_count, win_count from user where id=%d;"
        char sql[4096] = {0};
        sprintf(sql, USER_BY_ID, id);
        MYSQL_RES* res = nullptr;

        {
            std::unique_lock<std::mutex> lock(_mutex);
            bool ret = mysql_util::mysql_exec(_mysql, sql);
            if (ret == false)
            {
                DLOG("get user by id failed!");
                return false;
            }
            res = mysql_store_result(_mysql);
            if (res == nullptr)
            {
                DLOG("have no id info!");
                return false;
            }
        }
        
        int row_num = mysql_num_rows(res);
        if (row_num != 1)
        {
            DLOG("the user information queried is not unique!");
            return false;
        }
        MYSQL_ROW row = mysql_fetch_row(res);
        user["id"] = id;
        user["username"] = row[0];
        user["score"] = std::stol(row[1]);
        user["total_count"] = std::stoi(row[2]);
        user["win_count"] = std::stoi(row[3]);
        mysql_free_result(res);
        return true;
    }
    bool win(uint16_t id)
    {
#define USER_WIN "update user set score=score+30, total_count=total_count+1, win_count=win_count+1 where id=%d;"
        char sql[4096] = {0};
        sprintf(sql, USER_WIN, id);
        bool ret = mysql_util::mysql_exec(_mysql, sql);
        if (ret == false)
        {
            DLOG("update win user info failed!");
            return false;
        }
        return true;
    }
    bool lose(uint16_t id)
    {
#define USER_LOSE "update user set score=score-30, total_count=total_count+1 where id=%d;"
        char sql[4096] = {0};
        sprintf(sql, USER_LOSE, id);
        bool ret = mysql_util::mysql_exec(_mysql, sql);
        if (ret == false)
        {
            DLOG("update lose user info failed!");
            return false;
        }
        return true;
    }
    ~user_table()
    {
        mysql_util::mysql_destroy(_mysql);
        _mysql = nullptr;
    }
private:
    MYSQL* _mysql;
    std::mutex _mutex;
};

#endif